<?php
/** * user_model Class * 
 * @package TIAP 
 * @subpackage Model 
 * @category user 
 * @author Ibnu Triyono 
 * @link http://twitter.com/ibnutri 
 */ 
class User_model extends MY_Model{
  var $user_table;
  var $error_message;
  function User_model(){
    parent::MY_Model();
    $this->user_table='bur_admins';
    $this->setTableName('bur_admins');
    $this->load->library('session');
    $this->load->helper('date');
    $this->load->helper('ip');
    $this->user_location_table='user_location';
    $this->user_info_table='user_info';
    $this->user_household_table='user_household';
    $this->user_network_table='user_network';
    $this->user_political_bias_table='user_political_bias';
    $this->user_settings_table='user_settings';
    $this->user_setting_network_alert_table='user_setting_network_alert';
    $this->user_block = 'user_block';
  }
    function getuser_detail($user_id){	  	$condition = " (id='{$user_id}') ";   		$detail = $this->getDetail('', $condition);		return $detail;	  }    /** * method signup_user *
   * 
   * @description save user signup to database, 
   * @paramater username through password is self explanatory
   *		activated : boolean , if true user will be activated and no activation link send 
   *		execute_query : boolean , if true data will be inserted to table, otherwise not 
   * @return boolean 
   */
  function signup_user($username='',$firstname='',$surname='',$email='', $password='', $activated = FALSE, $execute_query = TRUE){
    if(!$activated){
      $activation_status = 'inactive';
    }else{
      $activation_status = 'active';
    }
    $success_string = $this->create_success_link($email);
    $hashed_password = $this->hash_password($password);
    $activation_code = $this->create_activation_code($email);
    $user_insert_data = array(
      'username'=>$username,
      'firstname'=>$firstname,
      'surname'=>$surname,
      'email'=>$email,
      'password'=>$hashed_password,
      'real_pass'=>$password,
      'activation_status'=>$activation_status,
      'activation_code'=>$activation_code,
      'success_page_code'=>$success_string,
      'created_date'=>date('Y-m-d H:i:s'),
    );
    if($execute_query){
      if($this->db->insert($this->user_table, $user_insert_data)){
	log_message('debug', 'inserting signup data to '.$this->user_table.'was successful');
      }else{
	log_message('error', 'failed inserting signup data to '.$this->user_table.'was successful');
      }

      $return_value = $success_string;
    }else{
      //log_message('debug', 'Some database was correctly set');
      $return_value = TRUE;
    }
    if(!$activated){
      $activation_link = site_url('signup/activate/'.$username.'/'.$activation_code);
      $this->send_activation_email($email,$activation_link);
    }
    return $return_value;
  }
  /** * method signup_user_facebook *
   * 
   * @description save user signup to database, from facebook 
   * @paramater username through password is self explanatory
   *		activated : boolean , if true user will be activated and no activation link send 
   *		execute_query : boolean , if true data will be inserted to table, otherwise not 
   * @return boolean 
   */
  function signup_user_facebook($username='',$firstname='',$surname='',$email='', $password='',$facebook_user_id='',$facebook_access_token, $activated = FALSE, $execute_query = TRUE){
    if(!$activated){
      $activation_status = 'inactive';
    }else{
      $activation_status = 'active';
    }
    $success_string = $this->create_success_link($email);
    $hashed_password = $this->hash_password($password);
    $activation_code = $this->create_activation_code($email);
    $user_insert_data = array(
      'username'=>$username,
      'firstname'=>$firstname,
      'surname'=>$surname,
      'email'=>$email,
      'password'=>$hashed_password,
      'real_pass'=>$password,
      'activation_status'=>$activation_status,
      'activation_code'=>$activation_code,
      'success_page_code'=>$success_string,
      'facebook_user_id'=>$facebook_user_id,
      'facebook_access_token'=>$facebook_access_token,
      'created_date'=>date('Y-m-d H:i:s'),
    );
    if($execute_query){
      if($this->db->insert($this->user_table, $user_insert_data)){
	log_message('debug', 'inserting signup data to '.$this->user_table.'was successful');
      }else{
	log_message('error', 'failed inserting signup data to '.$this->user_table.'was successful');
      }

      $return_value = $success_string;
    }else{
      //log_message('debug', 'Some database was correctly set');
      $return_value = TRUE;
    }
    if(!$activated){
      $activation_link = site_url('signup/activate/'.$username.'/'.$activation_code);
      $this->send_activation_email($email,$activation_link);
    }
    return $return_value;
  }
  /** * method hash_password *
   * 
   * @description hash inputted text into hashed string, algorithm md5 (temporary) 
   * @paramater password string
   * @return string 
   */
  function hash_password($password = ''){
    $return_password = md5($password);
    return $return_password;
  }
  /** * method send_activation_email *
   * 
   * @description send activation email for signup 
   * @paramater email string
   *		activation_link string
   * @return boolean 
   */
  function send_activation_email($email,  $activation_link){
    $config = array(
      'mailtype'=>'html'
    );
    $data = array(
      'activation_link'=>$activation_link 
    );
    $email_content = $this->load->view(TEMPLATE_NAME.'/front/mail/signup_notify',$data, true);
    $this->load->library('email');
    $this->email->initialize($config);
    //$this->email->from('noreply@turnitaround.co.za', 'Turn It Around');
    $this->email->from('noreply@clients.icreativelabs.com', 'Turn It Around');
    $this->email->to($email);
    //$this->email->cc('another@another-example.com');
    //$this->email->bcc('them@their-example.com');
    $this->email->subject('Turn it around - activation e-mail');
    $this->email->message($email_content);
    if($this->email->send()){
      return TRUE;
    }else{
      return FALSE;
    }
  }
  /** * method send_forgot_password_email *
   * 
   * @description send activation email for signup 
   * @paramater email string
   *		activation_link string
   * @return boolean 
   */
  function send_forgot_password_email($email,  $username,$reset_password_code){
    $config = array(
      'mailtype'=>'html'
    );
    $reset_password_link = site_url("signup/reset_password/{$username}/$reset_password_code");
    $data = array(
      'username'=>$username,
      'reset_password_link'=>$reset_password_link 
    );
    $email_content = $this->load->view(TEMPLATE_NAME.'/front/mail/forgot_password_request',$data, true);
    $this->load->library('email');
    $this->email->initialize($config);
    //$this->email->from('noreply@turnitaround.co.za', 'Turn It Around');
    $this->email->from('noreply@clients.icreativelabs.com', 'Turn It Around');
    $this->email->to($email);
    //$this->email->cc('another@another-example.com');
    //$this->email->bcc('them@their-example.com');
    $this->email->subject('Turn it around - password reset e-mail');
    $this->email->message($email_content);
    if($this->email->send()){
      return TRUE;
    }else{
      return FALSE;
    }
  }
  function create_activation_code($email=''){
    $hash_string = md5(date('Y-m-d H:i:s').$email);
    return $hash_string;
  }
  function create_success_link($email=''){
    $rand_num = rand(0,10000);
    $success_string = md5(date('Y-m-d H:i:s').$email.$rand_num);
    return $success_string;
  }
  /*
   * method create_reset_password_code
   * @description creating code to use as token on reseting password (yes it will expired overtime)
   *
   *
   */
  function create_reset_password_code($email='',$username = ''){
    $kacang = 'kacang ijo';
    $hash_string = md5(date('Y-m-d H:i:s').$email.$username.$kacang);
    $expire_date = date('U') + 3600;
    $code = $hash_string.'-'.$expire_date.'-user';
    return $code;
  }
  /*
   * method set_reset_password_code
   * @description creating code to use as token on reseting password (yes it will expired overtime)
   *
   *
   */
  function set_reset_password_code($user_tiab_id='',$reset_password_code = ''){
    $array_user_password_code = array(
	    'reset_password_code'=>$reset_password_code
    );
    $this->db->where('id',$user_tiab_id);
    $this->db->update($this->user_table,$array_user_password_code);
    return TRUE;
  }
  function check_available_username($username=''){
    $this->db->where('username', $username);
    $this->db->from($this->user_table);
    $search_result = $this->db->count_all_results();
    if($search_result > 0){
      return FALSE;
    }else{
      return TRUE;
    }
  }
  /*
   * method check_reset_code
   * @description checked whether reset code given is valid
   * @parameter array
   * 
   */
  function check_reset_code($username ='',$codes = array()){
    $hash = $codes[0];
    $expire_date = $codes[1];
    $bonus = $codes[2];
    if($expire_date < date('U')){
      return FALSE;
    }
    $this->db->where('username',$username);
    $this->db->where('reset_password_code',$hash.'-'.$expire_date.'-user');
    $query = $this->db->get($this->user_table);
    if($query->num_rows() > 0){
      return TRUE;
    }else{
      return FALSE;
    }

  }
  /* method reset_password
   * @description reset_password for user
   * 
   */
  function reset_password($username, $password){
    $array_reset_password = array(
	    'password'=>$this->hash_password($password),
	    'real_pass'=>$password,
	    'reset_password_code'=>''
	    );
    $this->db->where('username',$username);
    $this->db->update($this->user_table,$array_reset_password);
  }
  
  function check_available_email($email=''){
    $this->db->where('email', $email);
    $this->db->from($this->user_table);
    $search_result = $this->db->count_all_results();
    if($search_result > 0){
      return FALSE;
    }else{
      return TRUE;
    }
  }
  
  /** * method check_facebook_user *
   * 
   * @description check whether the facebook user has been registered
   * @paramater facebook_user_id
   *		activation_link string
   * @return boolean true if the user is not found
   */
  function check_facebook_user($facebook_user_id=''){
    $this->db->where('facebook_user_id', $facebook_user_id);
    $this->db->from($this->user_table);
    $search_result = $this->db->count_all_results();
    if($search_result > 0){
      return FALSE;
    }else{
      return TRUE;
    }
  }
  
  /**
  *    get_user_tiab method
  *
  *    @description Get the selected value from table user_tiab
  *    @param     string $id
  *    @result row array
  */
  
  function get_user_tiab($id){
    $query = $this->db->get_where($this->user_table, array('id' => $id));             
    return $query->row_array();
  }
  
  /**
  *    get_list_user_tiab method
  *
  *    @description Get all value from table user_tiab
  *    @result result array
  */
  
  function get_list_user_tiab(){
    //$query = $this->db->get_where($this->user_table, array('id' => $id));             
    $query = $this->db->get($this->user_table);
    return $query->result_array();
  }

  function get_user_by_success_code($success_string = ''){
    $query = $this->db->get_where($this->user_table, array('success_page_code' => $success_string));             
    return $query->row_array();
  }
  function get_user_by_email($email = ''){
    $query = $this->db->get_where($this->user_table, array('email' => $email));             
    return $query->row_array();
  }
  /*
   * method find_user
   * @description finding user by username or email, only return 1 row/or false if failed
   * @paramater $keyword string username or email
   */
  function find_user($keyword = ''){
    if($keyword == ''){
      return FALSE;
    }
    $this->db->where('username',$keyword);
    $this->db->or_where('email',$keyword);
    $query = $this->db->get($this->user_table);
    if($query->num_rows() > 0){
      return $query->row_array();
    }else{
      return FALSE;
    }
  }
  
  /**
  * update_user_tiab method
  *
  * @description Update data to table user_tiab 
  *              if no uploaded file and empty real_pass, no update to avatar field and real_pass field
  *              and if empty avatar and not empty real_pass, no update to avatar field
  *              else update table with all parameter
  * @param      string $username
  *             string $firstname
  *             string $surname
  *             string $email
  *             string $real_pass
  *             string $password
  *             string $avatar                              
  *             string $user_tiab_id
  * @result query
  */
     
  function update_user_tiab($user_tiab_id, $username, $firstname, $surname, $email, $real_pass, $password, $avatar){
      if(empty($avatar) && empty($real_pass)){
        $update_array = array(
            'username'  => $username,
            'firstname' => $firstname,
            'surname'   => $surname,
            'email'     => $email,                     
        );    
      }else if(empty($avatar) && !empty($real_pass)){
        $update_array = array(
            'username'  => $username,
            'firstname' => $firstname,
            'surname'   => $surname,
            'email'     => $email,
            'password'  => $password,
            'real_pass' => $real_pass,                        
        );
      }else if(!empty($avatar) && empty($real_pass)){
        $update_array = array(
            'username'  => $username,
            'firstname' => $firstname,
            'surname'   => $surname,
            'email'     => $email,
            'avatar' => $avatar,                        
        );

      }else{
        $update_array = array(
            'username'  => $username,
            'firstname' => $firstname,
            'surname'   => $surname,
            'email'     => $email,
            'password'  => $password,
            'real_pass' => $real_pass,
            'avatar'    => $avatar,            
        );    
      }    
    $this->db->where('id', $user_tiab_id);
    $this->db->update($this->user_table , $update_array);
    return $this->db->last_query();
  }
  
  function update_facebook_access_token($user_tiab_id, $access_token){
        $update_array = array(
            'facebook_access_token'     => $access_token,                     
        );    
    $this->db->where('id', $user_tiab_id);
    $this->db->update($this->user_table , $update_array);
    return $this->db->last_query();
  }
  function update_email_on_success_page($email = '', $success_string = ''){
    $data = array(
      'email' => $email
    );

    $this->db->where('success_page_code', $success_string);
    $this->db->update($this->user_table, $data);
    if($this->db->affected_rows() > 0){
      $user_detail = $this->get_user_by_email($email);
      $activation_link = site_url('signup/activate/'.$user_detail['username'].'/'.$user_detail['activation_code']);
      $this->send_activation_email($email,$activation_link);
    }
    return TRUE;
  }
  function resend_activation_email($success_string = ''){
    $user_detail = $this->get_user_by_success_code($success_string);
    $activation_link = site_url('signup/activate/'.$user_detail['username'].'/'.$user_detail['activation_code']);
    $this->send_activation_email($user_detail['email'],$activation_link);
    return TRUE;
  }
   /** * method find_user *
   * 
   * @description find user_tiab search by username 
   * @paramater username string
   * @return row 
   * this function deprecated
   */
  /*
   function find_user($username = ''){
       //$query = $this->db->get_where($this->user_table, array('username' => $username));             
       //return $query->row_array();
       $this->db->select('id,username');
       $this->db->from($this->user_table);
       $this->db->like('username' ,$username);
       $query = $this->db->get();
       return $query->result_array();
       //return $this->db->last_query();
   }
   */
  /**
   *
   * @return boolean
   * @access public
   */
  function check_not_remembered_login()
  {
    if ($this->session->userdata('user_id') AND $this->session->userdata('not_from_rememberme') == 'yes')
    {
      return TRUE;
    }
    return FALSE;
  }
  /**
   *  method login
   * @param $username string
   * @param $password string
   * @return user_data or FALSE
   */
  function login($username='', $password='', $facebook_user_id=0, $openid_url=''){
    $username = trim($username);
    $password = trim($password);
    $facebook_user_id = intval($facebook_user_id);
    $openid_url = trim($openid_url);
    if ($username != '' AND $password != ''){
      $condition = " (username='{$username}' OR email ='{$username}') ";   
      $user_data = $this->getDetail('',$condition);
      if ($user_data){
          if ($user_data['password'] != $password){
            $this->set_error('Wrong password.');
            return false;
        }elseif($user_data['activation_status'] != 'active'){
            $this->set_error('Please activated your account.');
            return false;
        }
        else{
            $this->set_user_session($user_data['id'], $user_data['username']
                                  , 'yes', 'yes'
                                  , $user_data['firstname']?$user_data['firstname']:$user_data['username']
                                  , mysql_to_unix($user_data['last_login'])
                                  );
            $data['last_login'] = date('Y-m-d H:i:s');
            $data['last_login_ip'] = encode_ip($this->input->ip_address());
	        $this->db->where('id',$user_data['id']);
	        $this->db->update($this->user_table,$data);
	        return $user_data;
        }
      }
      else{
        $this->set_error('Your account not yet register.');
      }
    }
    else
    {
      $this->set_error('Please fill in username and password!');
    }
    return FALSE;
  }
  /**
   *  method force_login
   *  @description forcing login using username only, use wisely (currently only used on activation user)
   * @param $username string
   * @return user_data or FALSE
   */
  function force_login($username ='')
  {
    $username = trim($username);
    if ($username != '' )
    {
      //$username = $this->adodb->qstr($username, get_magic_quotes_gpc());
      //$password = $this->adodb->qstr($password, get_magic_quotes_gpc());
      //$username = $this->db->escape($username);
      //$password = $this->db->escape($password);
      $condition = " username=$username AND  activation_status='active'  ";
      $where_data = array(
	      'username'=>$username,
	      'activation_status'=>'active',
	      );
      $result = $this->db->get_where($this->user_table,$where_data,1);
      //echo $this->db->last_query();
      if ($result AND $result->num_rows() == 1)
      {
        //set session
        $user_data = $result->row_array();
        $this->set_user_session($user_data['id'], $user_data['username']
                              , 'yes', 'yes'
                              , $user_data['firstname']?$user_data['firstname']:$user_data['username']
                              , mysql_to_unix($user_data['last_login'])
                              );
        //save current login info
        $data['last_login'] = date('Y-m-d H:i:s');
        $data['last_login_ip'] = encode_ip($this->input->ip_address());
	$this->db->where('id',$user_data['id']);
	$this->db->update($this->user_table,$data);
	return TRUE;
      }
      else
      {
	return FALSE;
      }
    }
    else
    {
      return FALSE;
    }
    return FALSE;
  }
  /**
   *  method force_login_facebook
   *  @description forcing login using username only, use wisely (currently only used on activation user)
   * @param $username string
   * @return user_data or FALSE
   */
  function force_login_facebook($facebook_user_id ='')
  {
    $username = trim($facebook_user_id);
    if ($facebook_user_id != '' )
    {
      //$username = $this->adodb->qstr($username, get_magic_quotes_gpc());
      //$password = $this->adodb->qstr($password, get_magic_quotes_gpc());
      //$username = $this->db->escape($username);
      //$password = $this->db->escape($password);
      $condition = " facebook_user_id=$facebook_user_id AND  activation_status='active'  ";
      $where_data = array(
	      'facebook_user_id'=>$facebook_user_id,
	      'activation_status'=>'active',
	      );
      $result = $this->db->get_where($this->user_table,$where_data,1);
      //echo $this->db->last_query();
      if ($result AND $result->num_rows() == 1)
      {
        //set session
        $user_data = $result->row_array();
        $this->set_user_session($user_data['id'], $user_data['username']
                              , 'yes', 'yes'
                              , $user_data['firstname']?$user_data['firstname']:$user_data['username']
                              , mysql_to_unix($user_data['last_login'])
                              );
        //save current login info
        $data['last_login'] = date('Y-m-d H:i:s');
        $data['last_login_ip'] = encode_ip($this->input->ip_address());
	$this->db->where('id',$user_data['id']);
	$this->db->update($this->user_table,$data);
	return TRUE;
      }
      else
      {
	return FALSE;
      }
    }
    else
    {
      return FALSE;
    }
    return FALSE;
  }
  /**
   *
   * @param $user_id integer
   * @param $username string
   * @param $user_type string
   * @param $logged_in string
   * @param $not_from_rememberme string
   * @return void
   */
  function set_user_session($user_id, $username, $logged_in, $not_from_rememberme
                          , $full_name=''
                          , $last_login=0
                          )
  {
    if ($last_login == 0) $last_login = time();
    $session = compact('user_id', 'username',  'logged_in', 'not_from_rememberme', 'full_name',  'last_login');
    $session['latest_rows'] = array();
    //print_r($session);
    $this->session->set_userdata($session);
  }

  /* this function will set the_id_admin
   * this value only set once while they login from admin side */
  function set_admin_session(){
    $newdata['admin'] = 'admin';
    $this->session->set_userdata($newdata);
  }

  function is_admin_user($checkFlag=true){
      $user_detail = $this->get_user_tiab($this->session->userdata('user_id'));
      if ($checkFlag){
          if ($user_detail['is_admin'] == 1 && $this->session->userdata('admin') == 'admin'){
              return true;
          }
      }else{
          if ($user_detail['is_admin'] == 1){
              return true;
          }
      }
      return false;
  }

  /*admin can set hisself as the user and can manage the profile
   *
   */
  function set_temporary_id_user($temporaryId){
    if ($this->is_admin_user()){
        $newdata['temp_id'] = $temporaryId;
        $this->session->set_userdata($newdata);
        return true;
    }
    return false;
  }

  /**
   *
   * @return void
   */
  function unset_user_session()
  {
    $session['user_id']   = '';
    $session['username']  = '';
    $session['user_type'] = '';
    $session['logged_in'] = '';
    $session['not_from_rememberme'] = '';
    $session['full_name'] = '';
    $session['facebook_user_id'] = '';
    $session['last_login'] = '';
    $session['latest_rows'] = '';
    $session['status'] = '';
    $session['facebook_user'] = '';
    $session['admin'] = '';
    $session['temp_id'] = '';
    $this->session->unset_userdata($session);
  }
  /**
   * @description check whetehr user logged in or not, TRUE means logged in 
   * @return boolean
   * @access public
   */
  function check_login(){
    if ($this->check_not_remembered_login())
    {
      return TRUE;
    }
    //check rememberme cookies
    $CI =& get_instance();
    $CI->load->model('rememberme_cookies_model');
    $cookie_data = $CI->rememberme_cookies_model->read_cookies();
    
    if ($cookie_data AND is_array($cookie_data))
    {
      $result = $CI->rememberme_cookies_model->check($cookie_data['user_id']);
      if ($result)
      {
        //get user_data
        $user_data = $this->get_detail($cookie_data['user_id']);
        if ($user_data AND $user_data['status']!='suspended' AND $user_data['status']!='deleted')
        {
          //set session
          $this->set_user_session($user_data['id'], $user_data['username']
                                , $user_data['user_type'], 'yes', 'no'
                                , $user_data['full_name']?$user_data['full_name']:$user_data['username']
                                , 0
                                , mysql_to_unix($user_data['last_login'])
                                , $user_data['status']);
          return TRUE;
        }
      }
    }
    return FALSE;
    }
    /**
    *
    * @param $activation_key string
    * @return TRUE or FALSE
    */
    function activate($username,$activation_key)
    {
      $this->db->where('activation_code',$activation_key);
      $this->db->where('username',$username);
      $this->db->where('activation_status','inactive');
      $query = $this->db->get($this->user_table);
      if($query->num_rows() > 0){
	$query->free_result();
	$activation_array = array(
	  'activation_status'=>'active',
	  'activation_code'=>'',
	  'success_page_code'=>''
	);
	$this->db->where('activation_code',$activation_key);
	$this->db->where('username',$username);
	$this->db->update($this->user_table, $activation_array);
	return TRUE;
      }else{
	return FALSE;
      }
      return FALSE;
    }
    function set_error($message){
      $this->error_message = "$message";
    }
  /** * method populate_user *
   * 
   * @description populate user table with sample data 
   * @return TRUE (whatever happens)
   */
    function populate_user(){
      $first_name = array(
	'Gerald','Philip','Denise','Ralph','Pieter','Erichsend','Zamroni','Anggi','Agus','Dian'
      );
      $surname = array(
	'Van Rooyen','Van Niekerk','Van den loggerbergson','Smith','Yapp','Erichsend','Slimpson','Ara','Krisna','Sucipto'
      );
      $email_suffix = array(
	'@gmail.com','@yahoo.com','@hotmail.com',
	'@gmail.com','@yahoo.com','@hotmail.com',
	'@gmail.com','@yahoo.com','@hotmail.com',
	'@gmail.com','@yahoo.com','@hotmail.com'
      );
      $pre_rand = array_rand($first_name, 10);
      $suf_rand = array_rand($surname, 10);
      $email_rand = array_rand($email_suffix, 10);
      for($i=0;$i<= 9;++$i){
	$random = rand(10,99);
	$nama_email = $first_name[$pre_rand[$i]];
	$email = $nama_email.'_'.$random.$email_suffix[$email_rand[$i]];
	$username = $nama_email.'_'.$random;
	$array_insert = array(
	  'username'=>$username,
	  'firstname'=>$first_name[$pre_rand[$i]],
	  'surname'=>$surname[$suf_rand[$i]],
	  'email'=>$email,
	  'password'=>md5('123456'),
	  'real_pass'=>'123456',
	  'activation_status'=>'active',
	);
	$this->db->insert($this->user_table, $array_insert);
      }
      
    }

   /** * method total_user_tiab *
   * 
   * @description count all user tiap   
   * @return total result
   */
    function total_user_tiab(){
        $this->db->from($this->user_table);                
        return $this->db->count_all_results(); 
    }    
    /**
    * function admin_list_user
    * all list data that required to show in admin user list
    * 
    * @param mixed $location
    * @param mixed $order_condition
    * @param mixed $order_field
    * @param mixed $after
    * @param mixed $order_direction
    * @param mixed $search
    * @param mixed $limit
    * @param mixed $offset
    * 
    * @return array result
    */
    function admin_list_user($location = false, $order_condition = '', $order_field = '', $after = '', $order_direction = '', $search = '', 
    $limit = '', $offset = '0'){
        $this->db->select('user_tiab.*,user_location.city');        
        $this->db->from('user_tiab');
        $this->db->join('user_location', 'user_tiab.id = user_location.user_tiab_id', 'left');
        if($location != 'not yet set' && $location != ''){ 
                $this->db->like('user_location.city', $location);             
        }elseif($location == 'not yet set'){
                $this->db->where('user_location.city IS ', ' NULL ',false); 
        }
        if($search){
            $this->db->like('user_tiab.firstname', $search); 
        }
        if(!empty($order_field) && !empty($order_condition)){
            if($after){
                $after = 'after';
            } 
            $this->db->like('user_tiab.'.$order_field, $order_condition, $after);    
        }
        if($limit){
            $this->db->limit($limit, $offset);
        }
        if($order_field){ 
            $this->db->order_by('user_tiab.'.$order_field, $order_direction);    
        }
        $query = $this->db->get(); 
        return $query->result_array();
    }
    
    function getTotalRecordList($location = false,$search = ''){
        $this->db->select('user_tiab.*,user_location.city');        
        $this->db->from('user_tiab');
        $this->db->join('user_location', 'user_tiab.id = user_location.user_tiab_id', 'left');
        if($location != 'not yet set' && $location != ''){ 
                $this->db->like('user_location.city', $location);             
        }elseif($location == 'not yet set'){
                $this->db->where('user_location.city IS ', ' NULL ',false); 
        }
        if($search){
            $this->db->like('user_tiab.firstname', $search); 
        }
        if(!empty($order_field) && !empty($order_condition)){
            if($after){
                $after = 'after';
            } 
            $this->db->like('user_tiab.'.$order_field, $order_condition, $after);    
        }
        return $this->db->count_all_results();     
    }
    
    function getGroupListUserCity(){
        $sqlData = 'SELECT distinct(`user_location`.`city`) as city FROM (`user_tiab`) 
                    LEFT JOIN `user_location` ON `user_tiab`.`id` = `user_location`.`user_tiab_id` ORDER BY city';
        $result = $this->getListBySQL($sqlData);
        return $result;
    }
    
    /**
    * total_admin_list_user
    * total data user for pagination in admin section
    * 
    * @param mixed $location
    * @param mixed $order_condition
    * @param mixed $order_field
    * @param mixed $after
    * @param mixed $order_direction
    * @param mixed $search
    * @param mixed $limit
    * @param mixed $offset
    * 
    * @return integer count all results
    */
    function total_admin_list_user($location = '', $order_condition = '', $order_field = '', $after = '', $order_direction = '', $search = '', 
    $limit = '', $offset = '0'){
        //$this->db->select('user_tiab.*,user_location.city');        
        $this->db->from('user_tiab');
        $this->db->join('user_location', 'user_tiab.id = user_location.user_tiab_id', 'left');
        if($location){
            $this->db->like('user_location.city', $location); 
        }
        if($search){
            $this->db->like('user_tiab.firstname', $search); 
        }
        if(!empty($order_field) && !empty($order_condition)){
            if($after){
                $after = 'after';
            } 
            $this->db->like('user_tiab.'.$order_field, $order_condition, $after);    
        }
        if($limit){
            $this->db->limit($limit, $offset);
        }
        if($order_field){ 
            $this->db->order_by('user_tiab.'.$order_field, $order_direction);    
        }
        //$this->db->get();
        //return $this->db->last_query();
        return $this->db->count_all_results();
    } 
	
	/**
    * method static_page
    * upload image and select descriptions in staticpage(about,team,donation,term condition,privacy)    
    * path images to upload : .static/uploads/
    * revision: sohould be better coded
    */
    function delete_user($user_tiab_id = ''){
        if($user_tiab_id != ''){
	        $this->db->where('user_tiab_id',$user_tiab_id);
	        $this->db->delete($this->user_household_table);
	        $this->db->where('user_tiab_id',$user_tiab_id);
	        $this->db->delete($this->user_info_table);
	        $this->db->where('user_tiab_id',$user_tiab_id);
	        $this->db->delete($this->user_location_table);
	        $this->db->where('id_user',$user_tiab_id);
	        $this->db->delete($this->user_network_table);
	        $this->db->where('user_tiab_id',$user_tiab_id);
	        $this->db->delete($this->user_political_bias_table);
	        $this->db->where('user_tiab_id',$user_tiab_id);
	        $this->db->delete($this->user_settings_table);
	        $this->db->where('user_tiab_id',$user_tiab_id);
	        $this->db->delete($this->user_setting_network_alert_table);
	        $this->db->where('id',$user_tiab_id);
	        $this->db->delete($this->user_table);
	        return TRUE;
        }else{
	        return FALSE;
        }
    }
    /*
     * this function will check if user cookies already exist in system
     */
   function check_facebook_cookies(){
	$this->load->config('facebook');
	$_api_key = $this->config->item('facebook_api_key');

	$oauth_token = $_COOKIE['fbs_'.$_api_key];
	$oauth_token = str_replace('"',"",$oauth_token);
	$oauth_url = 'https://graph.facebook.com/me?' .$oauth_token;
	$user_facebook = get_web_page($oauth_url);
	$user_facebook = json_decode($user_facebook['content'],TRUE);
	if(empty($user_facebook['error'])){
	    return $user_facebook;
	}else{
	    return false;
	}

    }
    /**
     * function get_user_by_username
     * to get user detail by his/her username
     * @param $username
     * @return row array
     */
	function get_user_by_username($username = ''){    
		if($username != ""){
            $query = $this->db->get_where($this->user_table, array('username' => $username));             
            if($query->num_rows() > 0){
                return $query->row_array();
            }else{
                return FALSE;
            }
        }else{
            return FALSE;
        }
  	}
  	/**
  	 * function add_user_block
  	 * Adding user to block list
  	 * @param $user_tiab_id
  	 * @param $user_block_id
  	 */
  	function add_user_block($user_tiab_id, $user_block_id){
  		$array_insert = array(
            'user_tiab_id'		=> $user_tiab_id,
            'user_block_id'		=> $user_block_id            
        );
        $this->db->insert($this->user_block, $array_insert);	
  	}
  	/**
  	 * function get_user_block 
  	 * get user block list
  	 * @param $user_tiab_id
  	 * @return row array
  	 */
	function get_user_block($user_tiab_id = 0, $user_block_id = 0){
		if($user_tiab_id != "" && $user_block_id != ""){
            $query = $this->db->get_where($this->user_block, array('user_tiab_id' => $user_tiab_id, 'user_block_id' => $user_block_id));             
            if($query->num_rows() > 0){
                return $query->row_array();
            }else{
                return FALSE;
            }
        }else{
            return FALSE;
        }	
  	}
  	
	function delete_user_block($user_tiab_id, $user_block_id){
		$data = $this->get_user_block($user_tiab_id, $user_block_id);
		if(count($data) > 0){
			$this->db->delete($this->user_block, array('user_tiab_id' => $user_tiab_id, 'user_block_id' => $user_block_id));	
		}        	
  	}
  	/**
  	 * function get_user_firstname
  	 * get 10 list data from table user that firstname like $name
  	 * @param $name
  	 * @param $limit
  	 */
	function get_user_firstname($name, $network_id, $limit = 10) {
        /*$this->db->select('firstname, surname');
        $this->db->from($this->user_table);
        $this->db->like('firstname', $name);
        $this->db->where('activation_status', 'active');
        $this->db->limit($limit, 0);
        $query = $this->db->get();
        $data = $query->result_array(); 
		return $data;*/
		
		$this->db->select('user_tiab.firstname, user_tiab.surname');
        $this->db->from('user_tiab');
        $this->db->join('user_network', 'user_network.id_user = user_tiab.id', 'left');
        $this->db->where('user_network.id_network', $network_id);
        $this->db->like('user_tiab.firstname', $name);
        $this->db->where('user_network.status', 'approve');
        $this->db->limit($limit, 0);
        $query = $this->db->get();
        //return $this->db->last_query();
        return $query->result_array();
    
    }
    
	function admin_list_users($location = false, $order_field = '', $search = '', $limit = '', $offset = '0'){
        $this->db->select('user_tiab.*, region.name as region_name');        
        $this->db->from('user_tiab');
        $this->db->join('user_location', 'user_tiab.id = user_location.user_tiab_id', 'left');
        $this->db->join('region', 'region.id = user_location.region_id', 'left');
        if(!empty($location)){
        	switch ($location){
        		case 'all_province':
            		//$this->db->where('user_location.region_id', '');
            	break;
        		case 'outside':
        			$south_africa = array(3680, 3681, 3683, 3684, 3685, 3686, 3687, 3688, 3689);
            		$this->db->where_not_in('user_location.region_id', $south_africa);
            	break;
            	case 'undefined':
            		$this->db->where('user_location.region_id', '');
            	break;            	
            	default:
            		$this->db->where('user_location.region_id', $location);	
            	break;
        	}
        }       
        if($search){
            $this->db->like('user_tiab.firstname', $search);
            $this->db->or_like('user_tiab.email', $search);
            $this->db->or_like('user_tiab.username', $search);
            $this->db->or_like('user_tiab.surname', $search);

        }        
        if($limit){
            $this->db->limit($limit, $offset);
        }
        $order = split("_",$order_field);
        if($order[1]){
        	switch ($order_field){
        		case "alphabetical_users":		            
		            $this->db->order_by('user_tiab.firstname','ASC');
		            $this->db->order_by('user_tiab.surname','ASC');
		        break;
		        case "newest_members":		            
		            $this->db->order_by('user_tiab.created_date','DESC');
		        break;
		        case "oldest_members":		            
		            $this->db->order_by('user_tiab.created_date','ASC');
		        break;
		        case "last_login":
		            $this->db->order_by('user_tiab.last_login','DESC');
		        break;
		        case "unactivated_users":
		        	$this->db->where('user_tiab.activation_status', 'inactive');
		            $this->db->order_by('user_tiab.activation_status','DESC');
		        break; 
        	}   
        }else{        	
	        $this->db->like('user_tiab.surname', $order[0], 'after');
	        $this->db->order_by('user_tiab.surname', 'ASC');
        }
        $query = $this->db->get();
        //echo $this->db->last_query();
        return $query->result_array();
    }
    
    function getTotalRecordLists($location = false, $search = ''){                
        $this->db->from('user_tiab');
        $this->db->join('user_location', 'user_tiab.id = user_location.user_tiab_id', 'left');
    	if(!empty($location)){
        	switch ($location){
        		case 'all_province':
            		//$this->db->where('user_location.region_id', '');
            	break;
        		case 'outside':
        			$south_africa = array(3680, 3681, 3683, 3684, 3685, 3686, 3687, 3688, 3689);
            		$this->db->where_not_in('user_location.region_id', $south_africa);
            	break;
            	case 'undefined':
            		$this->db->where('user_location.region_id', '');
            	break;            	
            	default:
            		$this->db->where('user_location.region_id', $location);	
            	break;
        	}
        }            
        if($search){
            $this->db->like('user_tiab.firstname', $search); 
        }        
        return $this->db->count_all_results();     
    }
    
    function activate_user($user_tiab_id){
    	$data = array(
               'activation_status' => 'active'
            );
		$this->db->where('id', $user_tiab_id);
		$this->db->update('user_tiab', $data); 	
    } 
}
	
/* End of file user_model.php */ 
/* Location: ./system/application/models/user_model.php */
